package edu.fiu.cis.personalize.server;

import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

public final class FBTokenStore {

	private static TimerTask cleanerTask = new TimerTask() {

		@Override
		public void run() {
			cleanExpiredSessions();

		}
	};

	static {
		Timer t = new Timer(true);
		t.scheduleAtFixedRate(cleanerTask, 0, 3600000);
	}

	static class Token {
		int uid;
		String accessToken;
		long expires;
		long issued;
	}

	private static ConcurrentHashMap<Integer, Token> tokenCache = new ConcurrentHashMap<Integer, FBTokenStore.Token>();

	public synchronized static void registerToken(int uid, String accessToken,
			long expires) {
		Token t = new Token();
		t.uid = uid;
		t.accessToken = accessToken;
		t.expires = expires;
		t.issued = System.currentTimeMillis();
		tokenCache.put(uid, t);
	}

	public static boolean isTokenValid(int uid) {
		Token t = tokenCache.get(uid);
		if (t != null) {
			return System.currentTimeMillis() - t.issued + t.expires > 0;
		}

		return false;
	}

	protected static synchronized void cleanExpiredSessions() {
		HashSet<Integer> uids = new HashSet<Integer>();
		for (Entry<Integer, Token> e : tokenCache.entrySet()) {
			if (!isTokenValid(e.getKey())) {
				uids.add(e.getKey());
			}
		}

		for (int i : uids) {
			tokenCache.remove(i);
		}
	}
}
